package com.mazong.serversecbasic.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    MyAuthenticationProvider authenticationProvider;

    @Resource
    MyFilterInvocationSecurityMetadataSource myFilterInvocationSecurityMetadataSource;

    @Resource
    MyAccessDecisionManager myAccessDecisionManager;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(authenticationProvider);

//        auth.inMemoryAuthentication()
//                .passwordEncoder(passwordEncoder())
//                .withUser("david")
//                .password(passwordEncoder().encode("123456"))
//                .authorities("ROLE_SELECT","ROLE_INSERT");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭csrf
        http.csrf().disable();

        http.authorizeRequests()

//                .antMatchers("/product/select").hasAuthority("USER")
//                .antMatchers("/product/insert").hasAuthority("USER")
//                .antMatchers("/product/update").hasAuthority("ADMIN")
//                .antMatchers("/product/delete").hasAuthority("ADMIN")
                .antMatchers("/login","/login-error").permitAll()
                .antMatchers("/**").fullyAuthenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(myFilterInvocationSecurityMetadataSource);
                        o.setAccessDecisionManager(myAccessDecisionManager);
                        return o;
                    }
                })
                .and()
                // 自定义登录页面
                .formLogin().loginPage("/login").failureUrl("/login-error").defaultSuccessUrl("/index")
                .and()
                // 没有登录，默认返回登录页面
                // 无权访问时：返回状态码403
                .exceptionHandling().accessDeniedPage("/403");
        // 登出授权
        http.logout().permitAll();
    }

    private PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
